package edu.cmu.cs.stage3.alice.authoringtool.viewcontroller;

import edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources;

/**
 * @author Jason Pratt
 */
public class FontPropertyViewController extends javax.swing.JButton implements edu.cmu.cs.stage3.alice.authoringtool.util.GUIElement, edu.cmu.cs.stage3.alice.authoringtool.util.Releasable {
	protected edu.cmu.cs.stage3.alice.core.Property property;
	protected boolean omitPropertyName;
	protected edu.cmu.cs.stage3.alice.core.event.PropertyListener propertyListener = new edu.cmu.cs.stage3.alice.core.event.PropertyListener() {
		public void propertyChanging( edu.cmu.cs.stage3.alice.core.event.PropertyEvent ev ) {}
		public void propertyChanged( edu.cmu.cs.stage3.alice.core.event.PropertyEvent ev ) {
			FontPropertyViewController.this.refreshGUI();
		}
	};

	public FontPropertyViewController() {
		addActionListener(
				new java.awt.event.ActionListener() {
					public void actionPerformed( java.awt.event.ActionEvent ev ) {
					}
				}
		);
	}

	public void set( edu.cmu.cs.stage3.alice.core.Property property, boolean omitPropertyName ) {
		clean();
		this.property = property;
		this.omitPropertyName = omitPropertyName;
		setBackground( AuthoringToolResources.getColor( "propertyViewControllerBackground" ) );
		setMargin( new java.awt.Insets( 0, 4, 0, 4 ) );
		startListening();
		refreshGUI();
	}

	public void goToSleep() {
		stopListening();
	}

	public void wakeUp() {
		startListening();
	}

	public void clean() {
		stopListening();
	}

	public void die() {
		stopListening();
	}

	public void release() {
		edu.cmu.cs.stage3.alice.authoringtool.util.GUIFactory.releaseGUI( this );
	}

	public void startListening() {
		if( property != null ) {
			property.addPropertyListener( propertyListener );
		}
	}

	public void stopListening() {
		if( property != null ) {
			property.removePropertyListener( propertyListener );
		}
	}

	protected void refreshGUI() {
		Object value = property.get();
		StringBuffer repr = new StringBuffer();

		if( ! omitPropertyName ) {
			repr.append( AuthoringToolResources.getReprForValue( property ) + " = " );
		}

		if( value instanceof edu.cmu.cs.stage3.alice.core.Expression ) {
			repr.append( AuthoringToolResources.getNameInContext( (edu.cmu.cs.stage3.alice.core.Element)value, property.getOwner() ) );
		} else if( value == null ) {
			repr.append( "<None>" );
		} else if( value instanceof java.awt.Font ) {
			java.awt.Font font = (java.awt.Font)value;
			repr.append( font.getFontName() );
		} else {
			throw new RuntimeException( "Bad value: " + value );
		}

		setText( repr.toString() );
		revalidate();
		repaint();
	}
}
